package com.fjnu.web;

import com.fjnu.entity.Category;
import com.fjnu.service.CategoryService;
import com.fjnu.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog-api/v0.1")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/category/delete")
    public ResponseResult delete(@RequestParam String categoryId) {
        try {
            log.info("删除分类 - 分类ID: {}", categoryId);

            int result = categoryService.deleteCategory(Integer.parseInt(categoryId));
            if (result > 0) {
                return ResponseResult.success("分类删除成功");
            } else {
                return ResponseResult.error("分类删除失败");
            }
        } catch (Exception e) {
            log.error("删除分类失败: {}", e.getMessage());
            return ResponseResult.error("删除分类失败");
        }
    }

    @PostMapping("/category/add")
    public ResponseResult add(@RequestBody Category category) {
        try {
            log.info("新增分类 - 分类名称: {}", category.getName());

            int result = categoryService.addCategory(category);
            if (result > 0) {
                return ResponseResult.success("分类添加成功");
            } else {
                return ResponseResult.error("分类添加失败");
            }
        } catch (Exception e) {
            log.error("新增分类失败: {}", e.getMessage());
            return ResponseResult.error("新增分类失败");
        }
    }

    @GetMapping("/category/list")
    public ResponseResult list() {
        try {
            log.info("查询分类列表");
            List<Category> categories = categoryService.getAllCategories();
            return ResponseResult.success(categories);
        } catch (Exception e) {
            log.error("查询分类列表失败: {}", e.getMessage());
            return ResponseResult.error("查询分类列表失败");
        }
    }
}